/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.ye;

import org.apache.flink.api.common.JobExecutionResult;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Skeleton for a Flink DataStream Job.
 *
 * <p>For a tutorial how to write a Flink application, check the
 * tutorials and examples on the <a href="https://flink.apache.org">Flink Website</a>.
 *
 * <p>To package your application into a JAR file for execution, run
 * 'mvn clean package' on the command line.
 *
 * <p>If you change the name of the main class (with the public static void main(String[] args))
 * method, change the respective entry in the POM.xml file (simply search for 'mainClass').
 */
public class DataStreamJob {

	public static void main(String[] args) throws Exception {
		// Sets up the execution environment, which is the main entry point
		// to building Flink applications.
		final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

		/*
		 * Here, you can start creating your execution plan for Flink.
		 *
		 * Start with getting some data from the environment, like
		 * 	env.fromSequence(1, 10);
		 *
		 * then, transform the resulting DataStream<Long> using operations
		 * like
		 * 	.filter()
		 * 	.flatMap()
		 * 	.window()
		 * 	.process()
		 *
		 * and many more.
		 * Have a look at the programming guide:
		 *
		 * https://nightlies.apache.org/flink/flink-docs-stable/
		 *
		 */
//		DataStreamSource<String> streamSource = env.fromElements("200", "100", "6000", "500", "2000", "300",
//				"1500", "900");

		DataStreamSource<String> streamSource = env.socketTextStream("host.docker.internal", 7777);
		// 对大于 500 和小于 500 进行分组
		KeyedStream<String, String> stringKeyedStream = streamSource.keyBy(new KeySelector<String, String>() {
			@Override
			public String getKey(String s) throws Exception {
				int i = Integer.parseInt(s);
				return i > 500 ? "ge" : "lt";
			}
		});

		// 开 10 秒滚动窗口，每 10 秒为一批数据 【00:00:00 ~ 00:00:10）、【00:00:10 ~ 00:00:20）左闭右开区间
		WindowedStream<String, String, TimeWindow> windowedStream = stringKeyedStream.window(
				TumblingProcessingTimeWindows.of(Time.seconds(10))
		);

		// 窗口处理函数，泛型 String, Integer, String, TimeWindow 依次对应 输入类型、输出类型、 KEY类型（即keyBy 返回的类型）, 窗口
		SingleOutputStreamOperator<Integer> outputStreamOperator =
				windowedStream.process(new ProcessWindowFunction<String, Integer, String, TimeWindow>() {
			/*
			 * key: 分组的 key
			 * context： 上下文信息
			 * elements： 传过来的一批数据
			 * out： 数据输出
			 * */
			@Override
			public void process(String key, ProcessWindowFunction<String, Integer, String, TimeWindow>.Context context,
								Iterable<String> elements, Collector<Integer> out) throws Exception {
				System.out.println(key);
				AtomicInteger sum = new AtomicInteger();
				elements.forEach(item -> sum.addAndGet(Integer.parseInt(item)));
				out.collect(sum.get());
			}
		});
		// 输出
		outputStreamOperator.print();

		// Execute program, beginning computation.
		JobExecutionResult jobExecutionResult = env.execute("Flink Java API Skeleton");
	}
}
